<template>
    <el-form ref="companyForm" :model="form" :rules="rules" label-width="120px" v-loading="loading">
        <el-form-item label="公司名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入公司名称" />
        </el-form-item>

        <el-form-item v-if="form.id" label="公司状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择状态">
                <el-option label="可用" :value="1" />
                <el-option label="不可用" :value="2" />
            </el-select>
        </el-form-item>

        <el-form-item label="联系电话" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>

        <el-form-item label="行业代码" prop="company_code">
            <el-input v-model="form.company_code" placeholder="请输入行业代码" />
        </el-form-item>

        <el-form-item label="行业名称" prop="sector_id">
            <el-cascader separator=" " filterable v-model="form.sector_id_array" :options="sector_classification"
                @change="handleSectorChange" :props="{
                    expandTrigger: 'hover'
                }" placeholder="请选择行业" class="sector-selector" clearable />
        </el-form-item>

        <el-form-item label="产品名称" prop="product_name">
            <el-input v-model="form.product_name" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="省市区" prop="location_id">
            <el-cascader separator=" " filterable v-model="form.location_id_array" :options="regionData"
                @change="handleLocationChange" :props="{
                    expandTrigger: 'hover'
                }" placeholder="请选择省市区" class="region-selector" clearable />
        </el-form-item>

        <el-form-item v-if="form.location_id_array.length > 0" label="详细地址" prop="location">
            <el-autocomplete v-model="form.location" :fetch-suggestions="queryLocationSuggestions" placeholder="请输入地址"
                @select="handleLocationSelect" :trigger-on-focus="false" clearable />
        </el-form-item>

        <template v-if="form.location">
            <el-form-item label="纬度" prop="latitude">
                <el-input v-model="form.latitude" placeholder="自动获取纬度" disabled />
            </el-form-item>

            <el-form-item label="经度" prop="longitude">
                <el-input v-model="form.longitude" placeholder="自动获取经度" disabled />
            </el-form-item>

            <el-form-item label="缩放比例" prop="zoom">
                <el-input v-model="form.zoom" placeholder="自动获取缩放比例" disabled />
            </el-form-item>
        </template>

        <el-form-item label="到期时间" prop="expire">
            <div class="expire-selector">
                <el-date-picker v-model="form.expire" type="datetime" placeholder="请选择到期时间" format="YYYY-MM-DD HH:mm:ss"
                    value-format="x" :disabled="form.neverExpire" clearable />
                <el-checkbox v-model="form.neverExpire" @change="handleNeverExpireChange">永不到期</el-checkbox>
            </div>
        </el-form-item>

        <el-form-item label="备注" prop="comment">
            <el-input resize="none" v-model="form.comment" placeholder="请输入备注" type="textarea" :rows="2" />
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="handleSubmit" :loading="loading">
                {{ form.id ? '修改' : '新增' }}
            </el-button>
            <el-button @click="handleReset">重置</el-button>
            <el-button v-if="form.id" type="danger" @click="handleDelete" :loading="loading">
                删除
            </el-button>
            <el-button v-if="showMapButton" type="success" @click="navigateToMap">
                在地图上显示
            </el-button>
        </el-form-item>
    </el-form>
</template>

<script setup>
import { computed, watch, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useLocationSearch } from '@/composables/useLocationSearch'
import { regionData, codeToText } from 'element-china-area-data'
import { useCompanyForm } from './composables/useCompanyForm'
import sector_classification from '@/assets/sector/sector_classification.json'

const props = defineProps({
    id: {
        type: [String, Number],
        default: null
    },
    latitude: {
        type: Number,
        default: null
    },
    longitude: {
        type: Number,
        default: null
    },
    zoom: {
        type: Number,
        default: 17
    }
})

const emit = defineEmits([
    'update:latitude',
    'update:longitude',
    'update:zoom',
    'location-change',
    'fetch-company-list'
])

const router = useRouter()
const route = useRoute()

const { queryLocationSuggestions } = useLocationSearch()

const {
    form,
    rules,
    loading,
    companyForm,
    fetchCompanyDetails,
    submitForm,
    deleteCompany,
    resetForm
} = useCompanyForm({
    defaultValues: {
        latitude: props.latitude,
        longitude: props.longitude,
        zoom: props.zoom
    },
    onSuccess: () => {
        ElMessage.success('操作成功')
        emit('fetch-company-list')
        let query = router.currentRoute.value.query
        if (query.from) {
            router.push({ name: query.from })
        }
    },
    onError: (error) => {
        console.error(error)
        ElMessage.error(error.message || '操作失败')
    },
    onDelete: () => {
        ElMessage.success('删除成功')
        router.push({ name: 'CompanyManagement' })
        emit('fetch-company-list')
    }
})

const showMapButton = computed(() =>
    route.name !== 'MapSelector'
)

const handleLocationSelect = (item) => {
    form.value.location = item.address
    form.value.latitude = item.location.lat
    form.value.longitude = item.location.lng

    emit('update:latitude', item.location.lat)
    emit('update:longitude', item.location.lng)
    emit('location-change', item.location.lat, item.location.lng)
}

// 处理到期时间"永不到期"复选框的变更
const handleNeverExpireChange = (checked) => {
    if (checked) {
        // 如果勾选"永不到期"，清除到期时间戳
        form.value.expire = 1
    }
}

// 处理行业选择变更
const handleSectorChange = (value) => {
    if (value && value.length > 0) {
        // 将选择的行业ID数组转换为以逗号分隔的字符串
        form.value.sector_id = value.join(',')
    } else {
        form.value.sector_id = ''
    }
}

// 处理地址选择变更
const handleLocationChange = (value) => {
    if (value && value.length > 0) {
        // 将选择的地区ID数组转换为以逗号分隔的字符串
        form.value.location_id = value.join(',')
    } else {
        form.value.location_id = ''
    }
}

const handleSubmit = async () => {
    try {
        await submitForm()
    } catch (error) {
    }
}

const handleDelete = async () => {
    try {
        await ElMessageBox.confirm('确定要删除该公司吗？', '提示', {
            type: 'warning',
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        })
        await deleteCompany()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error(error.message || '删除失败')
        }
    }
}

const handleReset = () => {
    ElMessageBox.confirm('确定要重置表单吗？', '提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
    }).then(() => {
        resetForm()
    }).catch(() => { })
}

const navigateToMap = () => {
    router.push({
        name: 'MapSelector',
        query: { id: form.value.id }
    })
}
watch(() => props.id, (newId) => {
    if (newId) {
        fetchCompanyDetails(newId)
    } else {
        resetForm()
    }
}, { immediate: true })

watch(() => props.latitude, (newLat) => {
    if (newLat !== form.value.latitude) {
        form.value.latitude = newLat
    }
})

watch(() => props.longitude, (newLng) => {
    if (newLng !== form.value.longitude) {
        form.value.longitude = newLng
    }
})

watch(() => props.zoom, (newZoom) => {
    if (newZoom !== form.value.zoom) {
        form.value.zoom = newZoom
    }
})
</script>

<style>
.expire-selector {
    display: flex;
    align-items: center;
    gap: var(--gap-normal);
}
</style>